package com.pp.demo.module.auth.service;

import com.pp.demo.module.auth.entity.AuthSystem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private AuthSystemService authSystemService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询系统信息
        AuthSystem authSystem = authSystemService.lambdaQuery()
                .eq(AuthSystem::getSystemName, username)
                .one();

        // 如果系统不存在，返回空
        if (authSystem == null) {
            log.warn("系统名称不存在");
            return null;
        }

        return createUserDetails(authSystem);
    }

    private UserDetails createUserDetails(AuthSystem authSystem) {
        // 创建权限列表
        List<GrantedAuthority> authorities = new ArrayList<>();

        // 假设系统角色名称为 "ROLE_SYSTEM_" + 系统ID
        // 实际应用中，应根据业务逻辑获取真实的权限信息
        authorities.add(new SimpleGrantedAuthority("ROLE_SYSTEM_" + authSystem.getSystemName()));

        // 或者可以直接使用系统名称作为权限
        authorities.add(new SimpleGrantedAuthority(authSystem.getSystemName()));

        return new User(
                authSystem.getSystemName(),
                authSystem.getPassword(),
                true,  // enabled
                true,  // accountNonExpired
                true,  // credentialsNonExpired
                true,  // accountNonLocked
                authorities
        );
    }
}
